use crate::socket_capnp::{map, peer_http_request, peer_http_response};
use anyhow::{anyhow, Result};
use capnp::message::{ReaderOptions, TypedBuilder, TypedReader};

use reqwest::header::{HeaderName, HeaderValue};
use serde_json::{json, Value};
use std::str::FromStr;

use tauri::ipc::IpcResponse;

use super::RobotEntity;

pub use rrai_desktop_sdk_common::devices::http_request;

pub async fn execute(token: &String, robot_id: u32, request: Value) -> Result<String> {
    //{\"action\":\"/ai/chat\",\"data\":{\"messages\":[{\"content\":\"你是谁？\",\"role\":\"user\"}],\"model\":\"gpt-4\",\"robot_id\":2},\"from\":\"5912088e48bc40ac84622b330e84175f\"}
    //通过robot_id获取RobotEntity
    let robot: RobotEntity = super::robots::_get_robot_by_id(token, robot_id).await?;

    let url = &robot.url;
    //
    let messages_value = if robot.request_jmespath != "" {
        //
        let expr = jmespath::compile(robot.request_jmespath.as_str())?;
        let result = expr.search(request)?;
        json!(result)
    } else {
        request
    };
    tracing::debug!("请求的消息体:{}", messages_value);
    //调用
    let response = reqwest::Client::new()
        .post(url)
        //Token
        .header(robot.token_key.as_str(), robot.token_value.as_str())
        .json(&messages_value)
        .send()
        .await
        .map_err(|err| anyhow!("请求失败:{}", err))?;

    let response_str = response.text().await?;

    tracing::debug!("返回的结果:{}", response_str);
    //
    if robot.response_jmespath != "" {
        //
        let expr = jmespath::compile(robot.response_jmespath.as_str())?;
        let data = jmespath::Variable::from_json(&response_str).unwrap();
        let result = expr.search(data)?;
        tracing::debug!("{}", result);
        Ok(json!(result).to_string())
    } else {
        Ok(response_str)
    }
}
